import sys
import os
import shutil
import webbrowser
from com.garmin.utils import util, http
import re

TEMP_DIR = "crashreporter_temp"
ANR_DIR = os.path.join(TEMP_DIR, "anr")
def start(file=None):
    ret = True
    if file is None:
        ret = util.pullCrashReport(TEMP_DIR)
        ret = util.pullANRReport(ANR_DIR)
    else:
        ret = util.copyCrashReport(file, TEMP_DIR)
    if not ret:
        exit(0)
    if util.compressDir(TEMP_DIR, "upload_temp.zip"):
        print "Compress files success!"
    else:
        print "Can not compress the file. Please make sure you have 7zip in your computer"
    try:
        http_buffer = http.post("upload_temp.zip")
        print http_buffer
        line_arr = http_buffer.split("\n")
        pattern = re.compile('URL:(.*)')
        for line in line_arr:
             match = pattern.match(line)
             if match:
                 webbrowser.open(match.group(1))
                 break;
    except IOError:
        print "Post to server error!"
    os.remove("upload_temp.zip")
    shutil.rmtree(TEMP_DIR)
    raw_input('Press enter key end...')
if __name__ == '__main__':
    if len(sys.argv) > 1:
        file = sys.argv[1]
        if os.path.exists(file):
            start(file)
            exit(0)
        else:
            raw_input('Error command argument')
    start()
